package com.example.nfcschool;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.ActionBar;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.nfc.NfcEvent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import android.content.Intent;
import android.net.wifi.WifiManager;

public class SViewActivity extends Activity implements OnClickListener,
		CreateNdefMessageCallback, OnNdefPushCompleteCallback {
	String telno = "";
	long time = 0;
	SRecordVO rvo;
	String cntIn = ""; // 지각 수
	String cntOut = ""; // 조퇴 수

	TextView irum_tx;
	TextView modi_tx;
	TextView grade_tx;
	TextView tel_tx;
	TextView birth_tx;
	TextView late_tx;
	TextView miss_tx;
	TextView leave_tx;
	TextView adds_tx;

	SmemberVO premem;
	private NfcAdapter mNfcAdapter; // NfcAdapter 를 선언
	boolean cheeting = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		ConnectData();
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sview2);

		ActionBar actionBar = getActionBar();
		actionBar.hide();

		irum_tx = (TextView) findViewById(R.id.irum_text);
		grade_tx = (TextView) findViewById(R.id.grade_text);
		tel_tx = (TextView) findViewById(R.id.tel_text);
		birth_tx = (TextView) findViewById(R.id.birth_text);
		late_tx = (TextView) findViewById(R.id.late_text);
		miss_tx = (TextView) findViewById(R.id.miss_text);
		leave_tx = (TextView) findViewById(R.id.leave_text);
		adds_tx = (TextView) findViewById(R.id.adds_text);
		modi_tx = (TextView) findViewById(R.id.modi_textbtn);
		Intent intent = getIntent();
		telno = intent.getStringExtra("tel");

		// Toast.makeText(this, "telno:" + telno, 2000).show();
		// new networkcut().execute();

		// SDBHelper db = new SDBHelper(this, "1myDB", null, 1);
		// SmemberVO d = db.select(telno); //위랑 두 줄 주석처리.

		// irum_tx.setText(d.getIrum());
		// grade_tx.setText(d.getGrade());
		// tel_tx.setText(d.getTel());
		// birth_tx.setText(d.getBirth());
		modi_tx.setOnClickListener(this);

		// 아래 2줄은 안드로이드빔을 성공적으로 전송했을 경우 이벤트 호출을 위해서 작성
		mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
		mNfcAdapter.setNdefPushMessageCallback(this, this);
		mNfcAdapter.setOnNdefPushCompleteCallback(this, this);

	}

	public void ConnectData() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
		try {
			Class localClass = connectivityManager.getClass();
			Class[] arrayOfClass = new Class[1];
			arrayOfClass[0] = Boolean.TYPE;
			Method localMethod = localClass.getMethod("setMobileDataEnabled",
					arrayOfClass);
			ConnectivityManager localConnectivityManager = connectivityManager;
			Object[] arrayOfObject = new Object[1];
			arrayOfObject[0] = Boolean.valueOf(true);
			localMethod.invoke(localConnectivityManager, arrayOfObject);
			WifiManager wifiManager = (WifiManager) getApplicationContext()
					.getSystemService(Context.WIFI_SERVICE);
			wifiManager.setWifiEnabled(true);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void DisconnectDATA() {

		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
		try {
			Toast.makeText(getApplicationContext(), "네트워크 차단 열공하세요!",
					Toast.LENGTH_LONG).show();
			Class localClass = connectivityManager.getClass();
			Class[] arrayOfClass = new Class[1];
			arrayOfClass[0] = Boolean.TYPE;
			Method localMethod = localClass.getMethod("setMobileDataEnabled",
					arrayOfClass);
			ConnectivityManager localConnectivityManager = connectivityManager;
			Object[] arrayOfObject = new Object[1];
			arrayOfObject[0] = Boolean.valueOf(false);
			localMethod.invoke(localConnectivityManager, arrayOfObject);
			WifiManager wifiManager = (WifiManager) getApplicationContext()
					.getSystemService(Context.WIFI_SERVICE);
			wifiManager.setWifiEnabled(false);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		new SelectOneJsp().execute();
		new RecentRecordJsp().execute();
		new AttendCheckJsp().execute();

	}

	// String-> NdefRecord로 바꾸는 메소드.
	public NdefRecord createTextRecord(String text) {
		byte[] data = text.getBytes();
		return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT,
				new byte[0], data);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		Intent intent = null;
		switch (id) {
		case R.id.LOGOUT:
			FileOutputStream fos = null;
			try {
				fos = openFileOutput("auto", Activity.MODE_PRIVATE);
				String data = "0";
				fos.write(data.getBytes());
				fos.close();
				// Toast.makeText(this, "파일이 저장되었습니다.",
				// Toast.LENGTH_SHORT).show();
			} catch (Exception ex) {
				Log.e("파일 save 에러", ex.toString());
			}
			finish();
			intent = new Intent(this, MainActivity.class);
			startActivity(intent);
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.modi_textbtn:
			cheeting = false;
			// Toast.makeText(this, "회원정보수정", Toast.LENGTH_SHORT).show();
			Intent intent = new Intent(this, SModifyActivity.class)
					.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			intent.putExtra("tel", telno);
			startActivity(intent);
			break;
		}
	}

	@Override
	public void onBackPressed() {
		if (System.currentTimeMillis() >= time + 2000) {
			Toast.makeText(this, "한 번 더 누르면 종료됩니다.", Toast.LENGTH_SHORT).show();
			time = System.currentTimeMillis();
		} else {
			finishAffinity();
		}
	}

	public void prn2(View v) {
		mHandler.obtainMessage(3).sendToTarget();

	}

	protected void onStart() {
		Typeface typeFace = Typeface.createFromAsset(getAssets(), "white.ttf");

		TextView tv = (TextView) findViewById(R.id.late_text);
		TextView tv1 = (TextView) findViewById(R.id.miss_text);
		TextView tv2 = (TextView) findViewById(R.id.leave_text);
		// TextView tv4 = (TextView) findViewById(R.id.textView2);
		TextView tv5 = (TextView) findViewById(R.id.modi_textbtn);
		TextView tv6 = (TextView) findViewById(R.id.adds_text);
		TextView tv7 = (TextView) findViewById(R.id.irum_text);
		TextView tv8 = (TextView) findViewById(R.id.grade_text);
		TextView tv9 = (TextView) findViewById(R.id.tel_text);
		TextView tv10 = (TextView) findViewById(R.id.birth_text);

		tv.setTypeface(typeFace);
		tv1.setTypeface(typeFace);
		tv2.setTypeface(typeFace);
		// tv4.setTypeface(typeFace);
		tv5.setTypeface(typeFace);
		tv6.setTypeface(typeFace);
		tv7.setTypeface(typeFace);
		tv8.setTypeface(typeFace);
		tv9.setTypeface(typeFace);
		tv10.setTypeface(typeFace);

		super.onStart();
	}

	// 자원 해제. Test 안해봄.
	// @Override
	// protected void onPause() {
	// // TODO Auto-generated method stub
	// super.onPause();
	// if (mNfcAdapter != null) {
	// mNfcAdapter.disableForegroundDispatch(this);
	// }
	// }

	@Override
	public void onNdefPushComplete(NfcEvent event) {
		if (rvo.getAttend().equals("true")) {
			mHandler.obtainMessage(1).sendToTarget();
		} else if (rvo.getAttend().equals("false")) {
			mHandler.obtainMessage(2).sendToTarget();
		}

	}

	@Override
	public NdefMessage createNdefMessage(NfcEvent event) {
		NdefMessage massage = new NdefMessage(
				new NdefRecord[] { createTextRecord(telno) });

		return massage;
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			FileOutputStream fos = null;
			switch (msg.what) {
			case 1:
				cheeting = false;
				fos = null;
				try {
					// 첫 매개변수는 파일명, 두번째 매개변수는 모드
					fos = openFileOutput("networkcheck", Activity.MODE_PRIVATE);

					String check1 = "true";
					fos.write(check1.getBytes());
					fos.close();
				} catch (Exception ex) {
					Log.e("파일 save 에러", ex.toString());
				}
				Toast.makeText(getApplicationContext(), "데이터 차단 열공하세요!",
						Toast.LENGTH_SHORT).show();
				DisconnectDATA();
				break;
			case 2:
				cheeting = false;
				Toast.makeText(getApplicationContext(), "하교합니당!", 2000).show();
				fos = null;
				try {
					// 첫 매개변수는 파일명, 두번째 매개변수는 모드
					fos = openFileOutput("networkcheck", Activity.MODE_PRIVATE);

					String check1 = "false";
					fos.write(check1.getBytes());
					fos.close();
				} catch (Exception ex) {
					Log.e("파일 save 에러", ex.toString());
				}
				break;
			}
		}
	};

	// ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡWEB DB
	public class SelectOneJsp extends AsyncTask<Void, String, Void> {

		String tag = "";
		StringBuilder sb = new StringBuilder();

		@Override
		protected Void doInBackground(Void... param) {

			try {

				Log.e("pre", "pre");
				try {
					HttpClient client = new DefaultHttpClient();
					String postURL = "http://192.168.0.7:8888/AndroidCheck/SelectOne.jsp";
					HttpPost post = new HttpPost(postURL);

					ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

					params.add(new BasicNameValuePair("tel", telno));

					UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,
							HTTP.UTF_8);
					post.setEntity(ent);
					HttpResponse responsePOST = client.execute(post);
					HttpEntity resEntity = responsePOST.getEntity();

					if (resEntity != null) {
						// Log.i("RESPONSE", EntityUtils.toString(resEntity));
						sb.append(EntityUtils.toString(resEntity));
					}
					client.getConnectionManager().shutdown(); // 추가된 코드.
				} catch (Exception ex) {
					Log.i("preeeee", ex.toString());
					Log.i("tel", sb.toString());
				}

				// 데이터 받기
				XmlPullParserFactory factory = XmlPullParserFactory
						.newInstance();
				factory.setNamespaceAware(true);
				XmlPullParser xpp = factory.newPullParser();
				xpp.setInput(new StringReader(sb.toString()));
				int eventType = xpp.getEventType();

				while (eventType != XmlPullParser.END_DOCUMENT) {// 현재 이벤트 타입이
																	// END_DOCUMENT를
																	// 만날때 까지
																	// 반복.

					switch (eventType) {
					case XmlPullParser.START_TAG: // 이벤트 타입에 START_TAG 라면.
						tag = xpp.getName(); // 태그 이름을 추출함.
						if (tag.equals("smember")) {
							premem = new SmemberVO();
						} else if (tag.equals("irum")) {
							premem.setIrum(xpp.nextText());
						} else if (tag.equals("tel")) {
							premem.setTel(xpp.nextText());
						} else if (tag.equals("picture")) {
							premem.setPicture(xpp.nextText());
						} else if (tag.equals("grade")) {
							premem.setGrade(xpp.nextText());
						} else if (tag.equals("pw")) {
							premem.setPw(Integer.parseInt(xpp.nextText())); // parse
																			// 되나?
						} else if (tag.equals("birth")) {
							premem.setBirth(xpp.nextText());
						} else if (tag.equals("teach")) {
							premem.setTeach(xpp.nextText());
						} else if (tag.equals("adds")) {
							premem.setAdds(xpp.nextText());
						} else if (tag.equals("sno")) {
							premem.setSno(xpp.nextText());
						}

						break;

					}
					eventType = xpp.next();
				}

			} catch (Exception e) {
				Log.e("SView Async Err", e.toString());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			Log.e("smodiend?", "send?");
			Log.e("premem.getTel", premem.getTel());

			String[] splitGrade = premem.getGrade().split("-");
			String year = premem.getBirth().substring(0, 4);
			String month = premem.getBirth().substring(4, 6);
			String day = premem.getBirth().substring(6, 8);

			String first = premem.getTel().substring(0, 3);
			String second = premem.getTel().substring(3, 7);
			String third = premem.getTel().substring(7, 11);

			irum_tx.setText(premem.getIrum());
			grade_tx.setText(splitGrade[0] + " 학년 " + splitGrade[1] + " 반");
			birth_tx.setText(year + "년" + month + "월" + day + "일");
			tel_tx.setText(first + "-" + second + "-" + third);
			adds_tx.setText(premem.getAdds());

			super.onPostExecute(result);
		}
	}

	public class RecentRecordJsp extends AsyncTask<Void, String, Void> {

		String tag = "";
		StringBuilder sb = new StringBuilder();

		@Override
		protected Void doInBackground(Void... param) {

			try {

				Log.e("pre", "pre");

				HttpClient client = new DefaultHttpClient();
				String postURL = "http://192.168.0.7:8888/AndroidCheck/RecentRecord.jsp";
				HttpPost post = new HttpPost(postURL);

				ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

				params.add(new BasicNameValuePair("tel", telno));

				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,
						HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);
				HttpEntity resEntity = responsePOST.getEntity();

				if (resEntity != null) {
					// Log.i("RESPONSE", EntityUtils.toString(resEntity));
					sb.append(EntityUtils.toString(resEntity));
				}
				client.getConnectionManager().shutdown(); // 추가된 코드.

				// 데이터 받기
				XmlPullParserFactory factory = XmlPullParserFactory
						.newInstance();
				factory.setNamespaceAware(true);
				XmlPullParser xpp = factory.newPullParser();
				xpp.setInput(new StringReader(sb.toString()));
				int eventType = xpp.getEventType();

				while (eventType != XmlPullParser.END_DOCUMENT) {// 현재 이벤트 타입이
																	// END_DOCUMENT를
																	// 만날때 까지
																	// 반복.

					switch (eventType) {
					case XmlPullParser.START_TAG: // 이벤트 타입에 START_TAG 라면.
						tag = xpp.getName(); // 태그 이름을 추출함.
						if (tag.equals("srecord")) {
							rvo = new SRecordVO();
						} else if (tag.equals("tel")) {
							rvo.setTel(xpp.nextText());
						} else if (tag.equals("attend")) {
							rvo.setAttend(xpp.nextText());
						} else if (tag.equals("instate")) {
							rvo.setInstate(xpp.nextText());
						} else if (tag.equals("intime")) {
							rvo.setIntime(xpp.nextText());
						} else if (tag.equals("outstate")) {
							rvo.setOutstate(xpp.nextText());
						} else if (tag.equals("outtime")) {
							rvo.setOuttime(xpp.nextText());
						}
						break;

					}

					eventType = xpp.next();
				}

			} catch (Exception e) {
				Log.e("SView Async Err", e.toString());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			Log.e("Main RecentRecord", "end?");
			if (rvo != null) {
				Log.d("rvo가 널은 아니야", "널 아니라고 ");
				Log.e("rvo.getAttend() ??", rvo.getAttend());
			} else {
				Log.e("RecentRecord Data가 ", "엄따!!!!!!!");
			}
			super.onPostExecute(result);
		}
	}

	public class AttendCheckJsp extends AsyncTask<Void, String, Void> {

		String tag = "";
		StringBuilder sb = new StringBuilder();

		@Override
		protected Void doInBackground(Void... param) {

			try {

				Log.e("pre", "pre");

				HttpClient client = new DefaultHttpClient();
				String postURL = "http://192.168.0.7:8888/AndroidCheck/AttendCheck.jsp";
				HttpPost post = new HttpPost(postURL);

				ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

				params.add(new BasicNameValuePair("tel", telno));

				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,
						HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);
				HttpEntity resEntity = responsePOST.getEntity();

				if (resEntity != null) {
					// Log.i("RESPONSE", EntityUtils.toString(resEntity));
					sb.append(EntityUtils.toString(resEntity));
				}
				client.getConnectionManager().shutdown(); // 추가된 코드.

				// 데이터 받기
				XmlPullParserFactory factory = XmlPullParserFactory
						.newInstance();
				factory.setNamespaceAware(true);
				XmlPullParser xpp = factory.newPullParser();
				xpp.setInput(new StringReader(sb.toString()));
				int eventType = xpp.getEventType();

				while (eventType != XmlPullParser.END_DOCUMENT) {// 현재 이벤트 타입이
																	// END_DOCUMENT를
																	// 만날때 까지
																	// 반복.

					switch (eventType) {
					case XmlPullParser.START_TAG: // 이벤트 타입에 START_TAG 라면.
						tag = xpp.getName(); // 태그 이름을 추출함.
						if (tag.equals("instate")) {
							cntIn = xpp.nextText();
						} else if (tag.equals("outstate")) {
							cntOut = xpp.nextText();
						}
						break;
					}
					eventType = xpp.next();
				}
			} catch (Exception e) {
				Log.e("SView Async Err", e.toString());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			Log.e("SView AttendCheck", "end?");
			late_tx.setText("지각 : " + cntIn + "회");
			leave_tx.setText("조퇴 : " + cntOut + "회");
			super.onPostExecute(result);
		}
	}

	@Override
	protected void onStop() {
		if (cheeting) {
			ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
			try {

				Class localClass = connectivityManager.getClass();
				Class[] arrayOfClass = new Class[1];
				arrayOfClass[0] = Boolean.TYPE;
				Method localMethod = localClass.getMethod(
						"setMobileDataEnabled", arrayOfClass);
				ConnectivityManager localConnectivityManager = connectivityManager;
				Object[] arrayOfObject = new Object[1];
				arrayOfObject[0] = Boolean.valueOf(false);
				localMethod.invoke(localConnectivityManager, arrayOfObject);
				WifiManager wifiManager = (WifiManager) getApplicationContext()
						.getSystemService(Context.WIFI_SERVICE);
				wifiManager.setWifiEnabled(false);

			} catch (Exception e) {
				e.printStackTrace();
			}//ddw
			FileOutputStream fos = null;
			Toast.makeText(getApplicationContext(), "네트워크 차단! 열공하세요!", 2000).show();
			fos = null;
			try {
				// 첫 매개변수는 파일명, 두번째 매개변수는 모드
				fos = openFileOutput("networkcheck", Activity.MODE_PRIVATE);

				String check1 = "true";
				fos.write(check1.getBytes());
				fos.close();
			} catch (Exception ex) {
				Log.e("파일 save 에러", ex.toString());
			}
		}
		super.onPause();
	}

}
